﻿using Data.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Data.DbContext;
using Repository.Interface;

namespace Repository
{
    /// <summary>
    /// 仓库操作基础类
    /// </summary>
    /// <typeparam name="TEntity">泛型实体</typeparam>
    public abstract class RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : EntityBase
    {
        #region 私有参数
        private readonly DbEntities _dbEntities = null;

        private readonly DbSet<TEntity> _dbSet = null; 
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        protected RepositoryBase()
        {
            _dbEntities = new DbEntities();
            _dbSet = _dbEntities.Set<TEntity>();
        } 
        #endregion

        #region 新增
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity">实体</param>
        public void Add(TEntity entity)
        {
            _dbSet.Add(entity);
            _dbEntities.SaveChanges();
        }
        #endregion

        #region 根据主键删除（逻辑删除）
        /// <summary>
        /// 根据主键删除（逻辑删除）
        /// </summary>
        /// <param name="id">主键</param>
        public void Delete(object id)
        {
            var entity = Get(id);
            if (entity == null) return;
            entity.IsDel = true;
            _dbEntities.SaveChanges();
        }
        #endregion

        #region 根据主键获取数据
        /// <summary>
        /// 根据主键获取数据
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>实体</returns>
        public TEntity Get(object id)
        {
            return _dbSet.Find(id);
        }
        #endregion

        #region 根据泛型委托获取所有数据
        /// <summary>
        /// 根据泛型委托获取所有数据
        /// </summary>
        /// <param name="func">泛型委托</param>
        /// <returns>实体集合</returns>
        public IList<TEntity> FindAll(Func<TEntity, bool> func)
        {
            return _dbSet.Where(c => !c.IsDel).Where(func).ToList();
        }
        #endregion
    }
}
